package studio.raptor.ddal.core.executor;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

/**
 * 批处理辅助执行单元
 * Created by dell on 2017/10/10.
 */
public class BatchExecutionUnit{

    private Connection connection=null;
    private Statement statement=null;
    private PreparedStatement preparedStatement=null;

    private int[] batchSqlAffectedRows;// 每个分片上批处理影响行数
    private List<int[]> batchSqlAffectedList;
    private int jdbcAndActualAddBatchCallTimes;// 每个分片上addBatch次数

    public BatchExecutionUnit(){
        this.batchSqlAffectedRows = new int[0];
        this.batchSqlAffectedList=new ArrayList<int[]>( );
        this.jdbcAndActualAddBatchCallTimes=0;
    }

    public BatchExecutionUnit(Connection connection){
        this.batchSqlAffectedRows = new int[0];
        this.batchSqlAffectedList=new ArrayList<int[]>( );
        this.jdbcAndActualAddBatchCallTimes=0;
        this.connection=connection;
    }

    public Connection getConnection() {
        return connection;
    }

    public void setConnection(Connection connection) {
        this.connection = connection;
    }

    public Statement getStatement() {
        return statement;
    }

    public void setStatement(Statement statement) {
        this.statement = statement;
    }

    public PreparedStatement getPreparedStatement() {
        return preparedStatement;
    }

    public void setPreparedStatement(PreparedStatement preparedStatement) {
        this.preparedStatement = preparedStatement;
    }

    public int getJdbcAndActualAddBatchCallTimes() {
        return jdbcAndActualAddBatchCallTimes;
    }

    public void setJdbcAndActualAddBatchCallTimes(int jdbcAndActualAddBatchCallTimes) {
        this.jdbcAndActualAddBatchCallTimes = jdbcAndActualAddBatchCallTimes;
    }

    public void addJdbcAndActualAddBatchCallTimes() {
        this.jdbcAndActualAddBatchCallTimes++;
    }

    public void addAffectedRowsOfShard(int[] affectedRowsOfShard) {
        this.batchSqlAffectedList.add( affectedRowsOfShard );
    }

    public int[] calcBatchSqlAffectedRows() {
        int size=0;
        for (int[] affectedRowsOfShard:batchSqlAffectedList) {
            size+=affectedRowsOfShard.length;
        }
        batchSqlAffectedRows=new int[size];
        int i=0;
        for (int[] affectedRowsOfShard:batchSqlAffectedList) {
            for (int result:affectedRowsOfShard) {
                batchSqlAffectedRows[i]=result;
                i++;
            }
        }
        return batchSqlAffectedRows;
    }

    public void setBatchSqlAffectedRows(int[] batchSqlAffectedRows) {
        this.batchSqlAffectedRows = batchSqlAffectedRows;
    }
}
